/*
 * Copyright (c) 2015-2019. Nuctech
 */

package android_serialport_api;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by 心魂free on 2019/10/30.
 * <p>
 * 谷歌串口
 */
public class SerialPort {

    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;
    //该变量必须为成员变量而且禁止修改名字,如果修改名字需要修改SerialPort.c文件的close内容，不然关闭串口会出问题
    private final FileDescriptor mFd;

    /**
     * 打开并配置串口
     *
     * @param device   串口设备的据对路径
     * @param baudrate 波特率
     * @param stopBits 停止位
     * @param dataBits 数据位
     * @param parity   校验位
     * @param flowCon  流控
     * @param flags    O_RDWR  读写方式打开 | O_NOCTTY  不允许进程管理串口 | O_NDELAY   非阻塞
     * @throws SecurityException 文件访问异常
     * @throws IOException       流异常
     */
    public SerialPort(File device, int baudrate, int stopBits, int dataBits, int parity, int flowCon, int flags) throws SecurityException, IOException {

        //检查文件句柄的读写权限
        if (!device.canRead() || !device.canWrite()) {

            try {

                Process su = Runtime.getRuntime().exec("/system/bin/su");
                String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                su.getOutputStream().write(cmd.getBytes());
                if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {

                    throw new SecurityException();
                }

            } catch (Exception e) {

                e.printStackTrace();
                throw new SecurityException();
            }
        }

        mFd = open(device.getAbsolutePath(), baudrate, stopBits, dataBits, parity, flowCon, flags);
        if (mFd == null) {

            throw new IOException();
        }

        //获取文件读写流
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    //JNI层串口开关
    private native static FileDescriptor open(String path, int baudrate,
                                              int stopBits, int dataBits,
                                              int parity, int flowCon, int flags);

    public native void close();

    static {

        System.loadLibrary("hardware_driver");
    }
}
